﻿using EYWeb.Core;
using EYWeb.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace EYWeb.WebLTE.App_Start.Handler
{
    public class MvcAuthorizeAttribute: ActionFilterAttribute
    {
        public RoleAuthorizeService roleAuthorizeService { get; set; }
        public bool Ignore { get; set; }
        public MvcAuthorizeAttribute(bool ignore=true)
        {
            Ignore = ignore;
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (OperatorProvider.Provider.GetCurrent() == null)
            {
                WebHelper.WriteCookie("login_error", "Overdue");
                filterContext.HttpContext.Response.Write("<script>top.window.location.href='/Login/Index'</script>");
            }

            //base.OnActionExecuting(filterContext);
            if (OperatorProvider.Provider.GetCurrent().IsSystem)
            {
                return;
            }
            if (!Ignore) return;
            if(!ActionAuthorize())
            {
                filterContext.Result = new ContentResult()
                {
                    //Content = "<script type='text/javascript'>alert('很抱歉！您的权限不足，访问被拒绝！');</script>"
                    Content = "<script type='text/javascript'>window.location.href='/Error/NoAccess';</script>", 
                };
                return;
            }

        }
        private bool ActionAuthorize()
        {
            OperatorModel _perator = OperatorProvider.Provider.GetCurrent();
            string roleId = _perator.RoleId;
            //string moduleId = WebHelper.GetCookie("nfine_currentmoduleid");
            string moduleId = WebHelper.GetCookie("eyweb_currentmoduleid");
            string action = HttpContext.Current.Request.ServerVariables["SCRIPT_NAME"].ToString();
            return roleAuthorizeService.ActionValidate(roleId, moduleId, action);

        }

    }
}